package com.outfood.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.outfood.common.eleme.ElemeOrder;
import com.outfood.common.eleme.Result;
import com.outfood.common.eleme.evaluate.ElemEvaluate;
import com.outfood.common.eleme.evaluate.OrderRateInfos;
import com.outfood.domain.ElemeEvaluateRecord;
import com.outfood.domain.EvaluateRecord;
import com.outfood.domain.Order;
import com.outfood.domain.Store;
import com.outfood.mapper.StoreMapper;
import com.outfood.service.IElemeEvaluateRecordService;
import com.outfood.service.IOrderService;
import com.outfood.service.IStoreService;
import com.outfood.utils.JavaScriptUtil;
import com.ruoyi.common.exception.BusinessException;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.Search;
import com.rys.common.utils.StringUtils;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.service.impl
 * @Date 2024-04-10 15:56
 * @Version 1.0
 */

@Log4j2
@Service
public class ElmeOperateServiceImpl {

        @Data
       public static class Query{
             private String ksid;
             private String shopId;
             private Long orderId;
             private Long storeId;
        }

        @Resource
        IStoreService storeService;

        @Resource
        CreateElemeTokenService createElemeTokenService;

        public List<Result> getOrderList(Query query){
            Store store = storeService.get(query.getStoreId());
            if(store.getPStoreId() != null && store.getOnlineStatus().equals("ONLINE")){
                log.info("如果父门存货，则子门店不用获取订单");
                return new ArrayList<>();
            }

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();

            String reqeustId = JavaScriptUtil.createRequestId();
            String params = "{\"service\":\"OrderWebService\",\"method\":\"queryInProcessOrders\",\"params\":{\"shopId\":"+query.getShopId()+",\"queryType\":\"COOKING\"},\"id\":\""+reqeustId+"\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+query.getKsid()+"\",\"shopId\":"+query.getShopId()+"},\"ncp\":\"2.0.0\"}";
            log.info("请求参数为{}",params);
            JSONObject jsonObject = JSON.parseObject(params);
            headers.add("path","/fulfill/weborder/queryInProcessOrders/?method=OrderWebService.queryInProcessOrders");
            headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
            headers.add("Bx-Et",createElemeTokenService.getsign());
            headers.add("X-Eleme-Requestid",reqeustId);
            headers.add("X-Shard","shopid="+query.shopId);




            HttpEntity request = new HttpEntity<>(jsonObject,headers);
            log.info("获取订单请求参数为{}",jsonObject);
            String url = "https://app-api.shop.ele.me/fulfill/weborder/queryInProcessOrders/?method=OrderWebService.queryInProcessOrders";
            ResponseEntity<String> jsonObjectResponseEntity = null;
            try {
                jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
            } catch (Exception e) {
                log.error("获取订单失败",e);
                if("401 Unauthorized".equals(e.getMessage())){
                    log.info("登录失效");
                    log.warn("门店{}登录失效",query.getStoreId());
                    if(store.getPStoreId() != null && store.getOnlineStatus().equals("ONLINE")){
                        log.info("父门店还存活，不用修改状态");
                    }else{
                        log.info("不存在父门店，直接设置离线");
                        store.setOnlineStatus("OFF");
                        store.setOffReason("401 Unauthorized");
                        storeService.update(store.getId(),store,"task");
                        meiTuanOperateService.downNotice(query.getStoreId());
                    }

                }
            }
            log.info(jsonObjectResponseEntity.getBody());
            ElemeOrder elemeOrder = JSON.parseObject(jsonObjectResponseEntity.getBody(), ElemeOrder.class);
            List<Result> result = elemeOrder.getResult();

            return CollectionUtils.isEmpty(result)?new ArrayList<>():result;
        }

    @Resource
    MeiTuanOperateServiceImpl meiTuanOperateService;


    @Resource
    RestTemplate restTemplate;

    //账号密码登录
    public com.outfood.common.common.Result loginByUsernamepassword(String username, String password){
        String result = restTemplate.getForObject("/usernamepasswordeleme?huburl=http://172.16.0.252:4444/wd/hub&username=" + username + "&password=" + password, String.class);
        log.info(result);

        com.outfood.common.common.Result optionResult = JSON.parseObject(result, com.outfood.common.common.Result.class);
//        SeleniumService seleniumService = new SeleniumServiceImpl();
//        com.outfood.common.common.Result optionResult = seleniumService.loginByPassword(username, password);
        if(!optionResult.isSuccess()){
            throw new BusinessException(optionResult.getMessage());
        }
        return optionResult;

    }


    //账号密码登录
    public com.outfood.common.common.Result loginByCode(String code){
        String result = restTemplate.getForObject("/loginByCodeEleme?code="+code, String.class);
        log.info(result);

        com.outfood.common.common.Result optionResult = JSON.parseObject(result, com.outfood.common.common.Result.class);
//        SeleniumService seleniumService = new SeleniumServiceImpl();
//        com.outfood.common.common.Result optionResult = seleniumService.loginByPassword(username, password);
        if(!optionResult.isSuccess()){
            throw new BusinessException(optionResult.getMessage());
        }
        return optionResult;

    }




    @Resource
    private IOrderService orderService;

    //查询所有带出餐的订单
    public OutResult excuteOutFood(Query query){
        Order order = orderService.get(query.getOrderId());
        RestTemplate restTemplate = new RestTemplate();
        String reqeustId = JavaScriptUtil.createRequestId();
        HttpHeaders headers = new HttpHeaders();
        headers.add("path","/fulfill/weborder/mealComplete/?method=ShipmentService.mealComplete");
        headers.add("Bx-Et",createElemeTokenService.getsign());
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
        headers.add("X-Eleme-Requestid",reqeustId);
        headers.add("X-Shard","shopid="+query.shopId);
        String params = "{\"service\":\"ShipmentService\",\"method\":\"mealComplete\",\"params\":{\"orderId\":\""+order.getOutTradeNo()+"\",\"shopId\":"+order.getPoiId()+"},\"id\":\""+reqeustId+"\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+query.getKsid()+"\",\"shopId\":"+order.getPoiId()+"},\"ncp\":\"2.0.0\"}";
        JSONObject jsonObject = JSON.parseObject(params);
        HttpEntity request = new HttpEntity<>(jsonObject,headers);
        String url = "https://app-api.shop.ele.me/fulfill/weborder/mealComplete/?method=ShipmentService.mealComplete";
        ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
        log.info("饿了么出餐结果为",jsonObjectResponseEntity.getBody());
        if(jsonObjectResponseEntity.getBody().contains("sessionStorage")){
            OutResult outResult = new OutResult();
            outResult.setError("000000");
            return outResult;
        }
        OutResult result = JSON.parseObject(jsonObjectResponseEntity.getBody(), OutResult.class);
        return result;

    }

    

    /**
     * Auto-generated: 2024-04-10 18:40:1
     *
     * @author bejson.com (i@bejson.com)
     * @website http://www.bejson.com/java2pojo/
     */
    @Data
    public static class OutResult {

        private String ncp;
        private String id;
        private String result;
        private String error;


    }


    @Resource
    IElemeEvaluateRecordService elemeEvaluateRecordService;


    public void getEvaluateList(Long storeId){
        Store store = storeService.get(storeId);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Bx-Et",createElemeTokenService.getsign());
        MeiTuanOperateServiceImpl.Range range = getRange();
        String params = "{\"service\":\"ShopRatingService\",\"method\":\"getRateResult\",\"params\":{\"rateQuery\":{\"shopIds\":["+store.getRegionId()+"],\"startTime\":\""+range.getStartTime()+"\",\"endTime\":\""+range.getEndTime()+"\",\"isReplied\":false,\"rateType\":\"ALL\",\"rateSourceType\":\"ELEME\",\"rateContentType\":\"ALL\",\"currentPage\":1,\"offset\":0,\"limit\":10}},\"id\":\"60236B7F18854A30B26BFC74715D4861|1715154506922\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+store.getCookie()+"\",\"shopId\":"+store.getRegionId()+"},\"ncp\":\"2.0.0\"}";
        JSONObject jsonObject = JSON.parseObject(params);
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
        HttpEntity request = new HttpEntity<>(jsonObject,headers);
        String url = "https://app-api.shop.ele.me/ugc/invoke/?method=ShopRatingService.getRateResult";
        ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
        ElemEvaluate elemEvaluate = JSON.parseObject(jsonObjectResponseEntity.getBody(), ElemEvaluate.class);
        elemEvaluate.getResult().getRateInfos().forEach(item -> {
            try {
                if(item.getOrderRateInfos().get(0).getRatingAt().getTime() + (1000*60*60*24*10) < new Date().getTime()){ //只对10天之前的评论进行保存
                    return;
                }
                try {
                    List<ElemeEvaluateRecord> list = elemeEvaluateRecordService.getList(new Search().add("evaluateId", SearchTypeEnum.EqualTo, item.getOrderRateInfos().get(0).getRateId()));
                    if(CollectionUtils.isNotEmpty(list)){
                        return;
                    }
                    System.out.println(JSON.toJSONString(item));
                    ElemeEvaluateRecord evaluateRecord = new ElemeEvaluateRecord();
                    evaluateRecord.setUserName(item.getUsername());
                    evaluateRecord.setCityName("");
                    evaluateRecord.setEcomment("");
                    evaluateRecord.setFoodName("");
                    OrderRateInfos orderRateInfos = item.getOrderRateInfos().get(0);

                    evaluateRecord.setPackagingScore(orderRateInfos.getPackageRating()+"");
                    evaluateRecord.setTasteScore(item.getDishScore()+"");
                    evaluateRecord.setUserPicUrl("");
                    evaluateRecord.setWmPoiId("");
                    evaluateRecord.setEvaluateTime(orderRateInfos.getRatingAt());
                    evaluateRecord.setDeliveryCommentScore(orderRateInfos.getServiceRating()+"");
                    evaluateRecord.setOrderCommentScore(orderRateInfos.getQualityRating()+"");
                    evaluateRecord.setEvaluateId(orderRateInfos.getRateId());
                    evaluateRecord.setReplayResult("NOT");
                    evaluateRecord.setOrderCommentScore(orderRateInfos.getQualityRating()+"");
                    evaluateRecord.setEvaluatePicUrl("");
                    evaluateRecord.setComment(orderRateInfos.getRatingContent());
                    evaluateRecord.setAuditStatus("");
                    evaluateRecord.setCommentType("");
                    evaluateRecord.setRemark(JSON.toJSONString(item));
                    evaluateRecord.setStoreId(store.getId());
                    elemeEvaluateRecordService.add(evaluateRecord,"task");
                } catch (Exception e) {
                    log.error("",e);
                    e.printStackTrace();
                }
            } catch (Exception e) {
                log.error("饿了么保存评价失败",e);
            }
        });

    }


    public void replay(Long evaluateId,String comment){
        ElemeEvaluateRecord elemeEvaluateRecord = elemeEvaluateRecordService.get(evaluateId);
        Store store = storeService.get(elemeEvaluateRecord.getStoreId());
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Bx-Et",createElemeTokenService.getsign());
        MeiTuanOperateServiceImpl.Range range = getRange();
        String params = "{\"service\":\"ShopRatingService\",\"method\":\"replyRating\",\"params\":{\"shopId\":"+store.getRegionId()+",\"reply\":{\"ratingComeFrom\":\"ELEME\",\"ratingId\":\""+elemeEvaluateRecord.getEvaluateId()+"\",\"ratingType\":\"ORDER\",\"content\":\""+comment+"\",\"templateId\":\"\"}},\"id\":\"44A655B30A3F436B92B042614DF8D903|1713172837446\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+store.getCookie()+"\",\"shopId\":"+store.getRegionId()+"},\"ncp\":\"2.0.0\"}";
        JSONObject jsonObject = JSON.parseObject(params);
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
        HttpEntity request = new HttpEntity<>(jsonObject,headers);
        String url = "https://app-api.shop.ele.me/ugc/invoke/?method=ShopRatingService.getRateResult";
        ResponseEntity<String> jsonObjectResponseEntity = null;
        try {
            jsonObjectResponseEntity  = restTemplate.postForEntity(url, request, String.class);
            log.info("饿了么评价结果返回{}",jsonObjectResponseEntity.getBody());
            if(!jsonObjectResponseEntity.getBody().contains("sessionStorage")){
                elemeEvaluateRecord.setReplayResult("HAS");
                elemeEvaluateRecord.setReplayMsg(comment);
                elemeEvaluateRecord.setEcomment(jsonObjectResponseEntity.getBody());
                elemeEvaluateRecordService.update(elemeEvaluateRecord.getId(),elemeEvaluateRecord,"task");
            }
        } catch (RestClientException e) {
            elemeEvaluateRecord.setReplayResult("EXCEPT");
            elemeEvaluateRecord.setReplayMsg(e.getMessage());
            elemeEvaluateRecord.setEcomment(jsonObjectResponseEntity.getBody());
            elemeEvaluateRecordService.update(elemeEvaluateRecord.getId(),elemeEvaluateRecord,"task");
        }
    }

//    public static void main(String[] args) {
//        ElmeOperateServiceImpl elmeOperateService = new ElmeOperateServiceImpl();
//        elmeOperateService.getEvaluateList(1L);
//    }
        public static MeiTuanOperateServiceImpl.Range getRange() {
            // 获取今天的日期和时间
            LocalDateTime today = LocalDateTime.now();

            // 获取前10天的日期和时间
            LocalDateTime tenDaysAgo = today.minusDays(10);

            // 定义日期和时间的格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'");

            // 格式化并打印今天的日期和时间
            String todayFormatted = today.format(formatter);
            System.out.println("Today: " + todayFormatted);

            // 格式化并打印前10天的日期和时间
            String tenDaysAgoFormatted = tenDaysAgo.format(formatter);
            System.out.println("10 days ago: " + tenDaysAgoFormatted);

            // 打印时间戳
            MeiTuanOperateServiceImpl.Range range = new MeiTuanOperateServiceImpl.Range();
            range.setStartTime(tenDaysAgoFormatted+"00:00:00");
            range.setEndTime(todayFormatted+"00:00:00");
            return range;
        }

}
